﻿$(function () {
    var GRID_DATA_KEY = 'orgin-data'; 
    if ($.jgrid) {
        $.extend($.jgrid.defaults || {}, {
            styleUI: 'Bootstrap',
            datatype: 'json',
            mtype: "POST",
            height: 450,
            autowidth: true,
            shrinkToFit: true,
            rowNum: 20,
            rownumbers: true,
            rowList: [10, 20, 50, 100],
            multiselect: true,
            pager: "#grid_pager",
            viewrecords: true,
            hidegrid: false,
            loadComplete: function (data) {

                //缓存原始数据
                var rows = data.rows;
                var key = $(this).jqGrid('getGridParam', 'keyName');
                var allData;
                if (rows.length > 0 && typeof rows[0][key] != 'undefined') {
                    allData = {};
                    for (var i = 0, len = rows.length; i < len; i++) {
                        allData[rows[i][key]] = rows[i];
                    }
                } else {
                    allData = rows;
                }

                $(this).data(GRID_DATA_KEY, allData);
            }
        });
    }

    $(document).ajaxError(function (event, request, settings) {
        toastr.error('数据请求异常');
    });

    //全局启用弹出模态框可拖动
    (function () {
        $(document).on('mousedown.drag', '.modal .modal-header', function (e) {
            var header = $(this);
            var dialog = $(this).closest('.modal');

            var pos_y = dialog.offset().top - e.pageY,
                  pos_x = dialog.offset().left - e.pageX;
            $(document).on("mousemove.drag", function (e) {
                dialog.offset({
                    top: e.pageY + pos_y,
                    left: e.pageX + pos_x
                });
            }).on("mouseup.drag", function () {
                $(this).off("mousemove.drag"); // Unbind events from document  
                $(this).off("mouseup.drag");
            });
            e.preventDefault(); // disable selection
        });
    })();
    
    $.postJsonAjax = function (url, data, success) {
        var hs = document.getElementsByName('__RequestVerificationToken');
        if (hs.length > 0) {
            data = data || {};
            data["__RequestVerificationToken"] = hs[0].value;
        }
        return $.ajax({
            url: url,
            cache: false,
            type: 'post',
            dataType: 'json',
            data: data,
            success: success
        });
    };

    $.confirm = function (msg, title, ok) {
        if (typeof title == 'function')
            ok = title;
        if (confirm(msg)) {
            ok();
        }
    };     

    $.fn.extend({
        //异步提交表单
        ajaxSubmit: function (success, failure) {
            form = $(this);
            $.ajax({
                url: form.attr('action'),
                cache: false,
                data: form.serialize(),
                type: 'post',
                dataType: 'json',
                success: function (result) {
                    if (result.Code != 1) {
                        toastr.error(result.Message);
                        return;
                    }
                    success(result);
                },
                failure: failure || function (m) {
                    console.warn(m);
                }
            });
        },

        //绑定数据
        bindData: function (data) {
            if (!data) {
                this[0].reset();
                $('[data-default]', this).each(function () {
                    $(this).val($(this).attr('data-default'));
                });
            } else {
                $('[name]', this).each(function () {
                    var name = $(this).attr('name');
                    if (typeof data[name] != 'undefined') {
                        if (typeof data[name] == 'boolean') {
                            this.checked = data[name]
                        }else{
                            $(this).val(data[name]);
                        }
                    }
                });
            }
        },

        //切换模态框的显示隐藏
        toggleModal: function (toggle, title) {
            if (typeof toggle == 'string') {
                $(this).modal('toggle');
                title = toggle;
            } else {
                if (toggle === true) {
                    $(this).modal('show');
                } else if (toggle === false) {
                    $(this).modal('hide');
                }
            }
            if (title) {
                $('.modal-header .modal-title', this).html(title);
            }
        }
    });

    //jqGrid扩展
    $.fn.getGridSelectedDatas = function () {
        var ids = this.jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0) return [];
        var all = this.data(GRID_DATA_KEY);
        var datas = [];
        for (var i = 0, len = ids.length; i < len; i++) {
            datas.push(all[ids[i]]);
        }
        return datas;
    };

    $.fn.getGridSelectedData = function () {
        var ids = this.jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0) return null; 
        var all = this.data(GRID_DATA_KEY);
        return all[ids[0]];
    };

    //适配grid的大小
    $.fn.adaptGridSizeInWindow = function () {
        var othis = this;
        var adjustGridSize = function () {
            var w = $(".jqGrid_wrapper").width();
            var h = $(document.body).height()
                - $('.jqGrid-toolbar').height()
                - $('.ui-jqgrid-titlebar').height()
                - $('.ui-jqgrid-hdiv').height()
                - $('.ui-jqgrid-sdiv').height()
                - $('.ui-jqgrid-pager').height();
            h -= 100; //pading
            othis.setGridWidth(w).setGridHeight(h);
        };

        $(window).bind("resize", adjustGridSize);

        adjustGridSize();
    };
    
    //toastr提示框插件配置
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "progressBar": true,
        "positionClass": "toast-top-center",
        "onclick": null,
        "showDuration": "400",
        "hideDuration": "600",
        "timeOut": "2000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }
});

